import { HttpError, toSuccess, useEntityManager } from "@sker/core"
import { AutoUser, KsDevice, KsLiveRoomLog } from "@sker/entities"
import { useData } from "@sker/runtime"
import dayjs from "dayjs"
import { z } from "zod"

export default async () => {
    const input = z.object({
        token: z.string()
    })
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) {
            throw new HttpError(`登陆失效`)
        }
        if (user.replace_mobile) user.mobile = user.replace_mobile
        const startTime = dayjs().subtract(5, 'minute').toDate()
        const list = await m.createQueryBuilder()
            .select('count(1)', 'count')
            .addSelect('device.id', 'device_id')
            .from(KsLiveRoomLog, 'log')
            .leftJoin(KsDevice, 'device', 'device.uuid=log.uuid')
            .where('log.open_time>=:open_time', { open_time: startTime })
            .andWhere('device.owner=:owner', { owner: user.mobile })
            .andWhere(`log.status=:status`, { status: '1' })
            .groupBy(`device.id`)
            .execute()

        const devices = await m.createQueryBuilder()
            .select('device.id', 'device_id')
            .from(KsLiveRoomLog, 'log')
            .leftJoin(KsDevice, 'device', 'device.uuid=log.uuid')
            .andWhere('device.owner=:owner', { owner: user.mobile })
            .groupBy(`device.id`)
            .orderBy(`device.id`, 'ASC')
            .execute()
        const res = devices.filter(it => !list.find(item => item.device_id === it.device_id)).map(it => ({ device_id: it.device_id, count: 0 }))
        return toSuccess(res)
    })
}